package com.css.zfzx.fxpg.modules.rescue.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.fxpg.common.utils.BeanUtil;
import com.css.zfzx.fxpg.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.fxpg.modules.citycounty.repository.FxCityCountyNativeRepository;
import com.css.zfzx.fxpg.modules.citycounty.repository.entity.FxCityCountyEntity;
import com.css.zfzx.fxpg.modules.citycounty.viewobjects.FxCityCountyQueryParams;
import com.css.zfzx.fxpg.modules.rescue.repository.FxRescueNativeRepository;
import com.css.zfzx.fxpg.modules.rescue.repository.FxRescueRepository;
import com.css.zfzx.fxpg.modules.rescue.repository.entity.FxRescueEntity;
import com.css.zfzx.fxpg.modules.rescue.service.FxRescueService;
import com.css.zfzx.fxpg.modules.rescue.viewobjects.FxRescueQueryParams;
import com.css.zfzx.fxpg.modules.rescue.viewobjects.FxRescueVO;
import com.css.zfzx.fxpg.modules.surveyspot.repository.FxSurveySpotNativeRepository;
import com.css.zfzx.fxpg.modules.surveyspot.repository.entity.FxSurveySpotEntity;
import com.css.zfzx.fxpg.modules.surveyspot.viewobjects.FxSurveySpotQueryParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * @author leon
 * @date 2020-12-02
 */
@Service
@Slf4j
public class FxRescueServiceImpl implements FxRescueService {

    @Autowired
    private FxRescueRepository fxRescueRepository;
    @Autowired
    private FxRescueNativeRepository fxRescueNativeRepository;
    /**
     * 市县
     */
    @Autowired
    private FxCityCountyNativeRepository fxCityCountyNativeRepository;
    /**
     * 调查点
     */
    @Autowired
    private FxSurveySpotNativeRepository fxSurveySpotNativeRepository;

    @Override
    public JSONObject queryFxRescues(FxRescueQueryParams queryParams, int curPage, int pageSize) {
        Page<FxRescueEntity> fxRescuePage = this.fxRescueNativeRepository.queryFxRescues(queryParams, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(fxRescuePage);
        return jsonObject;
    }


    @Override
    public FxRescueEntity getFxRescue(String id) {
        FxRescueEntity fxRescue = this.fxRescueRepository.findById(id).orElse(null);
        return fxRescue;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxRescueEntity saveFxRescue(FxRescueEntity fxRescue) {
        String uuid = UUIDGenerator.getUUID();
        fxRescue.setId(uuid);
        fxRescue.setCreateUser(PlatformSessionUtils.getUserId());
        fxRescue.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        this.fxRescueRepository.save(fxRescue);
        return fxRescue;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxRescueEntity updateFxRescue(FxRescueEntity fxRescue) {
        fxRescue.setUpdateUser(PlatformSessionUtils.getUserId());
        fxRescue.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        String id = fxRescue.getId();
        FxRescueEntity one = fxRescueRepository.findById(id).get();
        BeanUtil.copyPropertiesIgnoreNull(fxRescue, one);
        this.fxRescueRepository.save(one);
        return fxRescue;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFxRescues(List<String> ids) {
        List<FxRescueEntity> fxRescueList = this.fxRescueRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(fxRescueList) && fxRescueList.size() > 0) {
            for (FxRescueEntity fxRescue : fxRescueList) {
                this.fxRescueRepository.delete(fxRescue);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public String exportExcel(FxRescueQueryParams queryParams, HttpServletResponse response) {
        try {
            List<FxRescueEntity> entities = fxRescueNativeRepository.listFxRescues(queryParams);
            // 深拷贝
            ArrayList<FxRescueVO> vos = new ArrayList<>();
            for (FxRescueEntity entity : entities) {
                FxRescueVO vo = new FxRescueVO();
                BeanUtils.copyProperties(entity, vo);
                vos.add(vo);
            }
            // 导出
            EasyPoiExcelUtil.exportExcel(vos, "市县救援数据", "市县救援数据", FxRescueVO.class, "市县救援数据.xlsx", response);
            return "导出成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    @Override
    public String importExcel(MultipartFile file) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置解析从第1+1+1行开始
            params.setTitleRows(1);
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<FxRescueVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), FxRescueVO.class, params);
            List<FxRescueVO> list = result.getList();
            // 批量新增
            HashMap<String, ArrayList> map = this.saveExcel(list);
            ArrayList<Integer> indexList = map.get("index");
            ArrayList<String> messageList = map.get("message");
            int errorSize = indexList.size();
            returnMsg.append("成功导入" + (result.getList().size() - errorSize) + "条，失败" + (result.getFailList().size() + errorSize) + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<FxRescueVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    FxRescueVO vo = iterator.next();
                    String error = "";
                    returnMsg.append("第" + vo.getRowNum() + "行" + vo.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            for (int i = 0; i < errorSize; i++) {
                returnMsg.append("第" + indexList.get(i) + "行" + messageList.get(i) + "<br/>");
            }
            return returnMsg.toString();
        } catch (RuntimeException e) {
            log.error(e.getMessage(), e);
            return e.getMessage();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            if ("库中该数据最多一条，请管理员清理数据库冗余数据！".equals(e.getMessage())) {
                return e.getMessage();
            } else {
                return "导入失败，请检查数据正确性";
            }
        }
    }

    @Override
    public String judgeRational(FxRescueEntity fxRescue) {
        String message = "OK";
        // 市县名称
        String cityCountyName = fxRescue.getCityCountyName();
        FxCityCountyQueryParams cityCountyQueryParams = new FxCityCountyQueryParams();
        cityCountyQueryParams.setCityCountyName(cityCountyName);
        List<FxCityCountyEntity> fxCityCountyEntities = fxCityCountyNativeRepository.listFxCityCountys(cityCountyQueryParams);
        if (CollectionUtils.isEmpty(fxCityCountyEntities)) {
            message = "市县名称不存在,请先在市县数据管理中添加市县名称!";
        } else {
            // 调查点名称
            String surveySpotName = fxRescue.getSurveySpotName();
            FxSurveySpotQueryParams spotQueryParams = new FxSurveySpotQueryParams();
            spotQueryParams.setCityCountyName(cityCountyName);
            spotQueryParams.setSurveySpotName(surveySpotName);
            List<FxSurveySpotEntity> surveySpotEntities = fxSurveySpotNativeRepository.listFxSurveySpots(spotQueryParams);
            if (CollectionUtils.isNotEmpty(surveySpotEntities)) {
                FxRescueQueryParams rescueQueryParams = new FxRescueQueryParams();
                BeanUtils.copyProperties(spotQueryParams, rescueQueryParams);
                // 救援数据
                List<FxRescueEntity> rescueEntities = fxRescueNativeRepository.listFxRescues(rescueQueryParams);
                if (CollectionUtils.isNotEmpty(rescueEntities)) {
                    message = "该市县名称:" + cityCountyName + "下的调查点名称:" + surveySpotName + "的救援数据已存在！";
                }
            } else {
                message = "调查点名称不存在,请先在调查点管理中添加调查点名称!";
            }
        }
        return message;
    }

    private HashMap<String, ArrayList> saveExcel(List<FxRescueVO> list) {
        HashMap<String, ArrayList> map = new HashMap<>();
        ArrayList<Integer> indexList = new ArrayList<>();
        ArrayList<String> messageList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            FxRescueEntity entity = new FxRescueEntity();
            FxRescueVO vo = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(vo, entity);
            String errorMessage = saveOrUpdate(entity);
            if (errorMessage.contains("不存在")) {
                indexList.add(i + 1);
                messageList.add(errorMessage);
            }
        }
        map.put("index", indexList);
        map.put("message", messageList);
        return map;
    }

    /**
     * 保存或者修改
     *
     * @param entity
     */
    private String saveOrUpdate(FxRescueEntity entity) {
        String message = "OK";

        // 市县名称
        String cityCountyName = entity.getCityCountyName();
        FxCityCountyQueryParams cityCountyQueryParams = new FxCityCountyQueryParams();
        cityCountyQueryParams.setCityCountyName(cityCountyName);
        List<FxCityCountyEntity> fxCityCountyEntities = fxCityCountyNativeRepository.listFxCityCountys(cityCountyQueryParams);
        // 第一步：判断市县名称是否存在
        if (CollectionUtils.isEmpty(fxCityCountyEntities)) {
            message = "市县名称不存在,请先在市县数据管理中添加市县名称!";
        } else {
            // 调查点名称
            String surveySpotName = entity.getSurveySpotName();
            FxSurveySpotQueryParams spotQueryParams = new FxSurveySpotQueryParams();
            // 市县名称是否和调查点关联，若关联则需要传下面该参数
            //spotQueryParams.setCityCountyName(cityCountyName);
            spotQueryParams.setSurveySpotName(surveySpotName);
            List<FxSurveySpotEntity> surveySpotEntities = fxSurveySpotNativeRepository.listFxSurveySpots(spotQueryParams);
            // 第一步：判断调查点名称是否存在
            if (CollectionUtils.isNotEmpty(surveySpotEntities)) {
                FxRescueQueryParams rescueQueryParams = new FxRescueQueryParams();
                BeanUtils.copyProperties(spotQueryParams, rescueQueryParams);
                // 救援数据
                List<FxRescueEntity> rescueEntities = fxRescueNativeRepository.listFxRescues(rescueQueryParams);
                if (CollectionUtils.isNotEmpty(rescueEntities)) {
                    if (rescueEntities.size() == 1) {
                        FxRescueEntity sourceEntity = rescueEntities.get(0);
                        BeanUtil.copyPropertiesIgnoreNull(entity, sourceEntity);
                        this.updateFxRescue(sourceEntity);
                    } else {
                        throw new RuntimeException("库中该数据最多一条，请管理员清理数据库冗余数据！");
                    }
                } else {
                    // 若查到数据为空，则新增
                    this.saveFxRescue(entity);
                }
            } else {
                message = "调查点名称不存在,请先在调查点管理中添加调查点名称!";
            }
        }
        return message;
    }

}
